
const Service = require('./base_service')

class CustomerServer extends Service {
  //查询所有用户
  index () {
    let queryString = `
      SELECT 
      id
      , status
      , account_name as "accountName"
      , account_alias as "accountAlias"
      , access_token as "accessToken"
      , create_time as "createTime" 
      FROM sys_account
      ORDER BY id
    `
    return new Promise((resolve, reject) => {
      this.postgreServer()
        .connect()
        .then(client => {
          client.query(queryString, (err, res) => {
            client.release()
            if (err) {
              return reject(err)
            }
            resolve(res)
          })
        })
        .catch(e => {
          this.ctx.logger.error(e)
        })
    })
  }
  //新建
  create (customer) {
    let { accountName, accountAlias, accessToken } = customer
    let queryString = `INSERT INTO 
      sys_account(account_name, account_alias, access_token)
      VALUES($1, $2, $3)
    `
    return new Promise((resolve, reject) => {
      this.postgreServer()
        .connect()
        .then(client => {
          client.query(
            queryString
            , [accountName, accountAlias, accessToken]
            , (err, res) => {
              client.release()
              if (err) return reject(err)
              resolve(res)
            }
          )
        })
        .catch(e => {
          this.ctx.logger.error(e)
        })
    })
  }
  update (customer) {
    let { id, accountName, accountAlias, accessToken, status = 1 } = customer
    let queryString = `
      UPDATE sys_account SET 
      account_name = $2
      , account_alias = $3
      , access_token = $4
      , status = $5 
      WHERE id = $1
    `
    return new Promise((resolve, reject) => {
      this.postgreServer()
        .connect()
        .then(client => {
          client.query(
            queryString
            , [id, accountName, accountAlias, accessToken, status]
            , (err, res) => {
              client.release()
              if (err) return reject(err)
              resolve(res)
            }
          )
        })
        .catch(e => {
          this.ctx.logger.error(e)
        })
    })
  }
}

module.exports = CustomerServer
